Online-Academy

Look, Read, Understand, Apply

Menu

OOAD - Object Oriented Analysis and Design

Observer Design Pattern Code_New

import java.util.*;
interface subject{
    public void addObserver(Observer ob);
    public void removeObserver(Observer ob);
    public void notifyObservers();
}

class publisher implements subject{
    private ArrayList obs;
    String status;
    public publisher(){
        obs = new ArrayList();
        status = "unknown";
    }
    public void addObserver(Observer ob){
        obs.add(ob);
    }
    public void removeObserver(Observer ob){
        obs.remove(ob);
    }
    public void notifyObservers(){
        for(Observer obj: obs){
            obj.updateStatus(status);
        }
    }
    public void updateStatus(String status){
        this.status = status;
        notifyObservers();
    }   
}

interface Observer{
    public void updateStatus(String status);
    public void showStatus();
}
class observers implements Observer{
    private String status;
    public void updateStatus(String status){
        this.status = status; 
    }
    public void showStatus(){
        System.out.println("Status of Publisher is: "+status);
    }
}

class ObserverPattern{
    public static void main(String[] arggg){
        publisher p = new publisher();
        Observer o1,o2,o3,o4;
        o1 = new observers();
        o2 = new observers();
        o3 = new observers();
        o4 = new observers();
        p.addObserver(o1);
        p.addObserver(o3);
        p.addObserver(o4);
        p.updateStatus("Available");
        o1.showStatus();
        o2.showStatus();
        o3.showStatus();
        o4.showStatus();
    }
}